<?php
class ModelReportReturn extends Model {
	public function getReturns($filter) {
		$sql = "SELECT MIN(r.date_added) AS date_start, MAX(r.date_added) AS date_end, COUNT(r.return_id) AS `returns` FROM `@@return` r";

		if ($filter->get('filter_return_status_id')) {
			$sql .= " WHERE r.return_status_id = " . (int)$filter->get('filter_return_status_id');
		} else {
			$sql .= " WHERE r.return_status_id > 0";
		}

		if ($filter->get('filter_date_start')) {
			$sql .= " AND DATE(r.date_added) >= '" . ES($filter->get('filter_date_start')) . "'";
		}

		if ($filter->get('filter_date_end')) {
			$sql .= " AND DATE(r.date_added) <= '" . ES($filter->get('filter_date_end')) . "'";
		}

		$group = $filter->get('filter_group', 'week');
		
		switch($group) {
			case 'day';
				$sql .= " GROUP BY DAY(r.date_added)";
				break;
			default:
			case 'week':
				$sql .= " GROUP BY WEEK(r.date_added)";
				break;
			case 'month':
				$sql .= " GROUP BY MONTH(r.date_added)";
				break;
			case 'year':
				$sql .= " GROUP BY YEAR(r.date_added)";
				break;
		}

		$sql .= $filter->limit();
		
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getTotalReturns($filter) {
		$group = $filter->get('filter_group', 'week');

		switch($group) {
			case 'day';
				$sql = "SELECT COUNT(DISTINCT DAY(date_added)) AS total FROM `@@return`";
				break;
			default:
			case 'week':
				$sql = "SELECT COUNT(DISTINCT WEEK(date_added)) AS total FROM `@@return`";
				break;
			case 'month':
				$sql = "SELECT COUNT(DISTINCT MONTH(date_added)) AS total FROM `@@return`";
				break;
			case 'year':
				$sql = "SELECT COUNT(DISTINCT YEAR(date_added)) AS total FROM `@@return`";
				break;
		}

		if ($filter->get('filter_return_status_id')) {
			$sql .= " WHERE return_status_id = " . (int)$filter->get('filter_return_status_id');
		} else {
			$sql .= " WHERE return_status_id > 0";
		}
		
		if ($filter->get('filter_date_start')) {
			$sql .= " AND DATE(date_added) >= '" . ES($filter->get('filter_date_start')) . "'";
		}
		
		if ($filter->get('filter_date_end')) {
			$sql .= " AND DATE(date_added) <= '" . ES($filter->get('filter_date_end')) . "'";
		}

		return $this->db->queryOne($sql);
	}
}
?>